package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import domain.Product;

public class ProductDao extends BaseDao{
	/**
	 * @param args
	 */
	@SuppressWarnings("rawtypes")
	public ArrayList select(String sql)throws Exception{
		ArrayList<Product>result =new ArrayList<Product>();
		Connection conn =null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		conn=getConnection();
		pstmt=conn.prepareStatement(sql);
		rs=pstmt.executeQuery();
		while(rs.next()){
			Product obj=new Product();
			obj.setProductid(rs.getString("productid"));
			obj.setCategory(rs.getString("category"));
			obj.setName(rs.getString("name"));
			obj.setDescn(rs.getString("descn"));
			result.add(obj);
		}
		rs.close();
		pstmt.close();
		conn.close();
		return result;	
	}
	public void insert(Product obj)throws Exception{
		Connection conn =null;
		PreparedStatement ps=null;
		conn=getConnection();
		String sql="insert into product values(?,?,?,?)";
		ps=conn.prepareStatement(sql);
		ps.setString(1, obj.getProductid());
		ps.setString(2, obj.getCategory());
		ps.setString(3, obj.getName());
		ps.setString(4, obj.getDescn());
		ps.executeUpdate();
		ps.close();
		conn.close();
	}
	public void update(Product obj)throws Exception{
		Connection conn =null;
		PreparedStatement ps=null;
		conn=getConnection();
		String sql="update product set category=?,name=?,descn=? where productid=?";
		ps=conn.prepareStatement(sql);
		ps.setString(1, obj.getCategory());
		ps.setString(2, obj.getName());
		ps.setString(3, obj.getDescn());
		ps.setString(4, obj.getProductid());
		ps.executeUpdate();
		ps.close();
		conn.close();
	}
	public void delete(Product obj)throws Exception{
		Connection conn =null;
		PreparedStatement ps=null;
		conn=getConnection();
		String sql="delete from product where productid=?";
		ps=conn.prepareStatement(sql);
		ps.setString(1, obj.getProductid());
		ps.executeUpdate();
		ps.close();
		conn.close();
	}
	@SuppressWarnings("rawtypes")
	public Product getProduct(String productId) throws Exception{
		Product obj=null;
		ArrayList list=select("select*from product where productid='"+productId+"'");
		if(list.size()>0){
			obj=(Product) list.get(0);
		}
		return obj;
	}
	
	@SuppressWarnings({ "rawtypes" })
	public Product[] getProductListByCategory(String categoryId) throws Exception{
		ArrayList list=select("select*from product where category='"+categoryId+"'");
		Product[] obj=new Product[list.size()];
		if(list.size()>0){		
			for(int i=0;i<list.size();i++){
				obj[i]=(Product) list.get(i);
			}
		}
		return obj;
	}

}
